﻿using System;
using System.Web;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Net;
using umbraco.BusinessLogic;

namespace FMFeedCache
{
    public partial class FeedCache : System.Web.UI.Page
    {
        private static String appVPath = @"\plugins\FergusonMoriyama\FeedCache\";
        private static String configFileName = "feeds.config";

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Expires = -1;
            Log.Add(LogTypes.Debug, -1, "Feed Cache starting");

            String umbracoVPath = ConfigurationManager.AppSettings["umbracoPath"];
            String umbracoPhysicalPath = Server.MapPath(umbracoVPath) + appVPath;
            String configFile = Path.Combine(umbracoPhysicalPath, configFileName);

            if (File.Exists(configFile))
            {
                XPathDocument Doc = new XPathDocument(configFile);
                XPathNavigator navigator = Doc.CreateNavigator();
                XPathNodeIterator iterator = navigator.Select("/feeds/feed");
                while (iterator.MoveNext())
                {
                    String url = iterator.Current.SelectSingleNode("url").Value;
                    String outputFilename = iterator.Current.SelectSingleNode("localFile").Value;

                    String outputFile = Path.Combine(umbracoPhysicalPath, outputFilename);

                    Log.Add(LogTypes.Debug, -1, "Found feed " + url);

                    String feedData = "";
                    try
                    {
                        WebRequest request = WebRequest.Create(url);
                        WebResponse response = request.GetResponse();
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        
                        feedData = reader.ReadToEnd();


                        Log.Add(LogTypes.Debug, -1, "Write feed to " + outputFile);
                        TextWriter tw = new StreamWriter(outputFile);
                        tw.Write(feedData);
                        tw.Close();

                    }
                    catch (Exception ex)
                    {
                        feedData = url+ ": " + ex.Message;
                        Log.Add(LogTypes.Error, -1, feedData);
                    }

                    // Response.Write(feedData);
                }
            }
        }
    }
}
